const User = require("../models/user");
const jwt = require("jsonwebtoken");
const path = require("path");

const secret = process.env.SECRET;
class HomeCtl {
  index(ctx) {
    ctx.body = "<h1>我是大首页</h1>";
  }

  async login(ctx) {
    ctx.verifyParams({
      name: {
        type: "string",
        required: true
      },
      password: {
        type: "string",
        required: true
      }
    });
    const user = await User.findOne(ctx.request.body);
    if (!user) {
      ctx.throw(401, "用户名或密码不正确");
    }
    const { _id, name } = user;
    const token = jwt.sign({ _id, name }, secret, { expiresIn: "1d" });
    ctx.body = { token, user };
  }

  upload(ctx) {
    const file = ctx.request.files.file;
    const basename = path.basename(file.path);
    ctx.body = { url: `${ctx.origin}/uploads/${basename}` };
  }
}
// 18853107722
// 370402195401181916

module.exports = new HomeCtl();
